<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>绿蜂巢农产品系统 - ${param.keyword != null ? '搜索结果' : '产品列表'}</title>
    <link rel="stylesheet" href="static/css/styles.css">

</head>
<body>
<jsp:include page="header.jsp" />

<main>
    <!-- 产品分类 -->
    <div class="category-container">
        <h2 class="category-title">产品分类</h2>
        <div class="categories">
            <div class="category" onclick="window.location.href='products'">全部产品</div>
            <div class="category">蔬菜</div>
            <div class="category">水果</div>
            <div class="category">粮油副食</div>
            <div class="category">坚果</div>
            <div class="category">肉类</div>
            <div class="category">海鲜水产</div>
            <div class="category">特色农产品</div>
        </div>
    </div>

    <!-- 搜索结果提示 -->
    <c:if test="${param.keyword != null}">
        <div class="search-result-info">
            <h3>搜索结果: <span class="keyword">"${param.keyword}"</span></h3>
            <c:if test="${empty products}">
                <p class="no-result">没有找到与 "${param.keyword}" 相关的产品</p>
            </c:if>
        </div>
    </c:if>

    <!-- 产品展示 -->
    <div class="products-container">
        <h2 class="products-title">${param.keyword != null ? '搜索结果' : '产品列表'}</h2>
        <div class="products-grid">
            <c:forEach items="${products}" var="product">
                <div class="product-card" onclick="window.location.href='product-detail?id=${product.id}'">
                    <div class="product-image">
                        <img src="<c:url value="/static/photo/${product.photo}"/>" alt="${product.name}">
                    </div>
                    <div class="product-info">
                        <h3 class="product-name">${product.name}</h3>
                        <p class="product-price">${product.price}</p>
                        <div class="product-actions">
                            <button class="add-to-cart" data-product-id="${product.id}" data-product-name="${product.name}" data-product-price="${product.price}">加入购物车</button>
                            <button class="buy-now" data-product-id="${product.id}" data-product-name="${product.name}" data-product-price="${product.price}">立即购买</button>
                        </div>
                    </div>
                </div>
            </c:forEach>
        </div>
    </div>
</main>

<jsp:include page="footer.jsp" />

<!-- 支付模态框 -->
<div id="paymentModal" class="payment-modal">
    <div class="payment-content">
        <div class="payment-header">
            <h3>确认支付</h3>
            <span class="close-btn" onclick="closePaymentModal()">&times;</span>
        </div>
        <div id="paymentProductInfo" class="payment-product-info">
            <!-- 产品信息将在这里动态填充 -->
        </div>
        <div class="payment-form">
            <h4>选择支付方式</h4>
            <div class="payment-method selected" onclick="selectPaymentMethod(this)">
                <input type="radio" name="paymentMethod" value="wechat" checked>

                <span>微信支付</span>
            </div>
            <div class="payment-method" onclick="selectPaymentMethod(this)">
                <input type="radio" name="paymentMethod" value="alipay">

                <span>支付宝</span>
            </div>
            <div class="payment-method" onclick="selectPaymentMethod(this)">
                <input type="radio" name="paymentMethod" value="card">

                <span>银行卡</span>
            </div>
            <button class="payment-button" onclick="processPayment()"><a href="http://localhost:8080/fengchao_war_exploded/products">立即支付</a></button>
        </div>
    </div>
</div>


<!-- 成功提示 -->
<div id="successMessage" class="success-message">
    <p>操作成功!</p>
</div>

<script>
    // 当前选中的产品ID
    let currentProductId = null;
    let currentProductName = null;
    let currentProductPrice = null;

    // 等待DOM加载完成
    document.addEventListener('DOMContentLoaded', function() {
        // 为所有"加入购物车"按钮添加事件监听
        document.querySelectorAll('.add-to-cart').forEach(button => {
            button.addEventListener('click', function(e) {
                // 阻止卡片的点击事件冒泡
                e.stopPropagation();

                // 获取产品信息
                const productId = this.getAttribute('data-product-id');
                const productName = this.getAttribute('data-product-name');
                const productPrice = this.getAttribute('data-product-price');

                // 添加到购物车
                addToCart(productId, productName, productPrice);
            });
        });

        // 为所有"立即购买"按钮添加事件监听
        document.querySelectorAll('.buy-now').forEach(button => {
            button.addEventListener('click', function(e) {
                // 阻止卡片的点击事件冒泡
                e.stopPropagation();

                // 获取产品信息
                const productId = this.getAttribute('data-product-id');
                const productName = this.getAttribute('data-product-name');
                const productPrice = this.getAttribute('data-product-price');

                // 打开支付模态框
                openPaymentModal(productId, productName, productPrice);
            });
        });
    });

    // 添加商品到购物车
    function addToCart(productId, productName, productPrice) {


        // 创建表单数据
        const formData = new FormData();
        formData.add('productId', productId);
        formData.add('productName',productName); // 修正拼写错误：proguctName -> productName
        formData.add('productPrice',productPrice);
        formData.add('quantity', 1);

        // 发送AJAX请求到后端Servlet
        fetch('/cart/add', {
            method: 'POST',
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                // 移除了原代码中的 hideLoading() 调用

                if (data.success) {
                    // 显示成功消息
                    showSuccessMessage('已添加到购物车!');

                    // 更新购物车数量显示
                    updateCartCount(data.cartCount);

                    // 2秒后跳转到购物车页面
                    setTimeout(() => {
                        window.location.href = 'cart';
                    }, 2000);
                } else {
                    alert('添加购物车失败: ' + data.message);
                }
            })
            .catch(error => {
                // 移除了原代码中的 hideLoading() 调用
                console.error('Error:', error);
                alert('添加购物车时发生错误');
            });
    }

    // 更新购物车数量显示
    function updateCartCount(count) {
        const cartCountElement = document.querySelector('.cart-count');
        if (cartCountElement) {
            cartCountElement.textContent = count;
        }
    }

    // 打开支付模态框
    function openPaymentModal(productId, productName, productPrice) {
        // 保存当前产品信息
        currentProductId = productId;
        currentProductName = productName;
        currentProductPrice = productPrice;

        // 更新支付模态框中的产品信息
        document.getElementById('paymentProductInfo').innerHTML = `
            <div class="payment-product">
                <p>商品: ${productName}</p>
                <p>价格: ${productPrice}</p>
                <p>数量: 1</p>
                <p class="total-amount">总计: ${productPrice}</p>
            </div>
        `;

        // 显示支付模态框
        document.getElementById('paymentModal').style.display = 'flex';
    }

    // 关闭支付模态框
    function closePaymentModal() {
        document.getElementById('paymentModal').style.display = 'none';
    }

    // 选择支付方式
    function selectPaymentMethod(element) {
        // 移除所有已选状态
        document.querySelectorAll('.payment-method').forEach(method => {
            method.classList.remove('selected');
        });

        // 添加当前选中状态
        element.classList.add('selected');
    }

    // 处理支付
    function processPayment() {
        // 获取选中的支付方式
        const paymentMethod = document.querySelector('input[name="paymentMethod"]:checked').value;

        // 移除了原代码中的 showLoading() 调用

        // 关闭支付模态框
        closePaymentModal();

        // 创建表单数据
        const formData = new FormData();
        formData.add('productId', currentProductId);
        formData.add('paymentMethod', paymentMethod);
        formData.add('quantity', 1);

        // 发送AJAX请求到后端Servlet
        fetch('/checkout/process', {
            method: 'POST',
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                // 移除了原代码中的 hideLoading() 调用

                if (data.success) {
                    // 显示成功消息
                    showSuccessMessage('支付成功!');

                    // 更新购物车数量显示
                    updateCartCount(data.cartCount);

                    // 2秒后跳转到订单确认页面
                    setTimeout(() => {
                        window.location.href = 'order-confirmation';
                    }, 2000);
                } else {
                    alert('支付失败: ' + data.message);
                }
            })
            .catch(error => {
                // 移除了原代码中的 hideLoading() 调用
                console.error('Error:', error);
                alert('支付过程中发生错误');
            });
    }

    // 显示成功消息
    function showSuccessMessage(message) {
        const successMessage = document.getElementById('successMessage');
        successMessage.querySelector('p').textContent = message;
        successMessage.style.display = 'block';

        // 3秒后隐藏成功消息
        setTimeout(() => {
            successMessage.style.display = 'none';
        }, 3000);
    }
</script>
</body>
</html>